<?php
declare (strict_types=1);

namespace emqx;

/**
 * emqx_HttpApi
 */
class EmqxHttpApi extends Emqx
{

    /**
     * 消息发布
     * @param string $topic
     * @param string|array $payload
     * @param int $qos
     * @return mixed
     */
    public function publish(string $topic, string|array $payload = 'HelloWorld', int $qos = 0): mixed
    {
        $data = [
            'topic' => $topic,
            'payload' => $payload,
            'qos' => $qos,
        ];
        //请求地址
        $url = $this->emqx_http_host . '/api/v4/mqtt/publish';
        //发送请求
        return $this->postUrl($url, json_encode($data));
    }

    /**
     * 发送get请求
     * @param string $url
     * @return mixed
     */
    private function getUrl(string $url): mixed
    {
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_USERPWD => "$this->emqx_appid:$this->emqx_secret",
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        return json_decode($response, true);
    }

    /**
     * 发送post请求
     * @param string $url
     * @param array|string $data
     * @return mixed
     */
    private function postUrl(string $url, array|string $data): mixed
    {
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $data,
            CURLOPT_USERPWD => "$this->emqx_appid:$this->emqx_secret",
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        return json_decode($response, true);
    }

}
